﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Urs.Core;
using Urs.Core.Caching;
using Urs.Data.Domain.Configuration;
using Plugin.Api.Extensions;
using Plugin.Api.Models.Catalog;
using Plugin.Api.Models.Media;
using Urs.Services.Stores;
using Urs.Services.Localization;
using Urs.Services.Media;
using Urs.Services.Security;
using Urs.Framework.Controllers;

namespace Plugin.Api.Controllers
{
    /// <summary>
    /// 商品分类接口
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/category")]
    [ApiController]
    public class CategoryController : BaseApiController
    {
        private readonly ILocalizationService _localizationService;
        private readonly IWorkContext _workContext;
        private readonly MediaSettings _mediaSettings;
        private readonly ICategoryService _categoryService;
        private readonly ICacheManager _cacheManager;
        private readonly IPictureService _pictureService;
        /// <summary>
        /// 构造器
        /// </summary>
        public CategoryController(ILocalizationService localizationService,
            IWorkContext workContext,
            MediaSettings mediaSettings,
            ICategoryService categoryService,
            ICacheManager cacheManager,
            IPictureService pictureService)
        {
            this._localizationService = localizationService;
            this._workContext = workContext;
            this._mediaSettings = mediaSettings;
            this._categoryService = categoryService;
            this._cacheManager = cacheManager;
            this._pictureService = pictureService;
        }

        #region Utilities

        [NonAction]
        protected List<int> GetChildCategoryIds(int parentCategoryId, bool showHidden = false)
        {
            var userRolesIds = _workContext.CurrentUser.UserRoles
                .Where(cr => cr.Active).Select(cr => cr.Id).ToList();
           
                var categoriesIds = new List<int>();
                var categories = _categoryService.GetAllCategoriesByParentCategoryId(parentCategoryId, showHidden);
                foreach (var category in categories)
                {
                    categoriesIds.Add(category.Id);
                    categoriesIds.AddRange(GetChildCategoryIds(category.Id, showHidden));
                }
                return categoriesIds;
           
        }

        [NonAction]
        protected MoPicture PrepareCategoryPictureModel(int categoryId, int categoryPictureId, string categoryName)
        {
            //prepare picture model
            int pictureSize = _mediaSettings.CategoryThumbPictureSize;
            
                var pictureModel = new MoPicture()
                {
                    BigUrl = _pictureService.GetPictureUrl(categoryPictureId),
                    NormalUrl = _pictureService.GetPictureUrl(categoryPictureId, pictureSize)
                };
                return pictureModel;
           
        }

        [NonAction]
        protected List<MoCategoryList> PrepareCategoryListModel(int rootCategoryId, bool loadsub)
        {
            var result = new List<MoCategoryList>();
            foreach (var category in _categoryService.GetAllCategoriesByParentCategoryId(rootCategoryId))
            {
                var categoryModel = new MoCategoryList()
                {
                    Id = category.Id,
                    Name = category.Name,
                };
                var picture = PrepareCategoryPictureModel(category.Id, category.PictureId, category.Name);
                if (picture != null)
                    categoryModel.ImageUrl = picture.NormalUrl;
                if (loadsub)
                    foreach (var item in _categoryService.GetAllCategoriesByParentCategoryId(category.Id))
                    {
                        categoryModel.SubCategories.AddRange(PrepareCategoryListModel(item.Id, loadsub));
                    }
                result.Add(categoryModel);
            }
            return result;
        }
        #endregion

        /// <summary>
        /// 获取首页商品分类
        /// </summary>
        /// <returns></returns>
        [HttpGet("homecategories")]
        public async Task<ApiResponse<List<MoCategory>>> GetHomepageCategories()
        {
            var categories = _categoryService.GetAllCategoriesDisplayedOnHomePage();
            
            var listModel = categories
                .Select(x =>
                {
                    var catModel = x.ToModel();
                    catModel.Description = null;
                    catModel.Picture = PrepareCategoryPictureModel(x.Id, x.PictureId, x.Name);

                    return catModel;
                })
                .ToList();

            return ApiResponse<List<MoCategory>>.Success(listModel);
        }
        /// <summary>
        /// 获取单个分类 
        /// </summary>
        /// <param name="id">商品分类Id</param>
        /// <returns></returns>
        [HttpGet("get")]
        public async Task<ApiResponse<MoCategory>> Get(int id)
        {
            var entity = _categoryService.GetCategoryById(id);

            if (entity == null)
                return ApiResponse<MoCategory>.NotFound();

            return ApiResponse<MoCategory>.Success(entity.ToModel());
        }
        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <param name="loadsub">加载子分类(默认:不加载)</param>
        /// <param name="catId">上级分类Id（默认:一级分类）</param>
        /// <returns></returns>
        [HttpGet("sublist")]
        public async Task<ApiResponse<List<MoCategoryList>>> GetList(bool loadsub = false, int catId = 0)
        {
            var list = new List<MoCategoryList>();
            var model = await Task.Run(() => PrepareCategoryListModel(catId, loadsub));
            return ApiResponse<List<MoCategoryList>>.Success(model);
        }


    }
}
